package main

import (
	//"errors"
	"iot-base/common/dbconn"
)

func getThingEx(qmap map[string]string) ([]map[string]interface{}, error) {

	sel := `select things.*,thing_stations.sno,thing_stations.station_id,stations.s_name as station_name,ipcs.*,
	stations.parent_id,thing_states.state,ipp.param_value as ip,unp.param_value as username,psp.param_value as password,
	portp.param_value as port,thing_maintain_infos.*,t_models.s_name as model_name,thing_states.state,
	thing_stations.sno,t_models.catalog_id`
	from := ` from things`
	join := ` left join thing_stations on thing_stations.thing_id = things.uid
	left join stations on stations.uid = things.uid
	left join thing_states on thing_states.thing_id = things.uid
	left join ipcs on ipcs.ipc_id = things.uid
	left join thing_params as ipp on ipp.param_id in ('IP','ip') and ipp.thing_id = things.uid
	left join thing_params as unp on unp.param_id ='username' and unp.thing_id = things.uid
	left join thing_params as psp on psp.param_id ='password' and psp.thing_id = things.uid
	left join thing_params as portp on portp.param_id ='port' and portp.thing_id = things.uid
	left join thing_maintain_infos on thing_maintain_infos.thing_id = things.uid
	left join t_models on t_models.uid=things.model_id`
	where := " where 1=1"

	stationID := qmap["station_id"]
	boxID := qmap["box_id"]

	if stationID != "" {
		//from += ",stations as st"
		where += `and things.uid in (
			select thing_id from thing_stations where thing_stations.station_id = '` + stationID + `')`
	}

	if boxID != "" {

		where += `and things.uid in (
			select ipc_id from ipcs where ipcs.box_id = '` + boxID + `')`

	}
	sql := sel + from + join + where + "order by things.uid"

	var res []map[string]interface{}
	err := dbconn.DBConnection.Raw(sql).Find(&res).Error
	return res, err
}
